'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import Image from 'next/image';
import { useSession } from 'next-auth/react';
import AppHeader from '@/components/ui/app-header';
import {
  PlusIcon,
  MagnifyingGlassIcon,
  FunnelIcon,
  ArrowsUpDownIcon,
  ClockIcon,
  CheckCircleIcon,
  ArrowPathIcon,
  ExclamationCircleIcon,
} from '@heroicons/react/24/outline';
import { cn } from '@/lib/utils';

// 项目状态标签组件
const StatusBadge = ({ status }: { status: string }) => {
  switch (status) {
    case 'completed':
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
          <CheckCircleIcon className="mr-1 h-4 w-4" />
          已完成
        </span>
      );
    case 'in-progress':
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
          <ArrowPathIcon className="mr-1 h-4 w-4" />
          进行中
        </span>
      );
    case 'planning':
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
          <ClockIcon className="mr-1 h-4 w-4" />
          规划中
        </span>
      );
    default:
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
          {status}
        </span>
      );
  }
};

// 项目类型定义
interface Project {
  id: string;
  name: string;
  description?: string;
  createdAt: string;
  updatedAt: string;
  owner?: {
    id: string;
    name: string;
    avatar?: string;
  };
  members?: {
    id: string;
    name: string;
    avatar?: string;
    role: string;
  }[];
  status: string;
  tags?: string[];
}

export default function ProjectListPage() {
  const router = useRouter();
  const { data: session, status: authStatus } = useSession();
  const [projects, setProjects] = useState<Project[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [filter, setFilter] = useState({
    status: 'all',
  });
  const [sort, setSort] = useState({
    field: 'updatedAt',
    direction: 'desc',
  });

  // 获取项目数据
  useEffect(() => {
    const fetchProjects = async () => {
      setLoading(true);
      setError(null);
      try {
        let url = '/api/project';
        if (session?.user?.id) {
          url += `?userId=${session.user.id}`;
        }
        
        // 添加时间戳防止缓存问题
        url += `${url.includes('?') ? '&' : '?'}t=${new Date().getTime()}`;
        
        console.log('获取项目列表, URL:', url);
        const response = await fetch(url, {
          cache: 'no-store', 
          headers: {
            'Cache-Control': 'no-cache',
            'Pragma': 'no-cache'
          }
        });
        if (!response.ok) {
          throw new Error(`请求失败: ${response.status}`);
        }
        
        const data = await response.json();
        console.log('项目列表响应:', data);
        
        if (data.success) {
          setProjects(data.data);
        } else {
          throw new Error(data.message || '获取项目失败');
        }
      } catch (err: any) {
        console.error('获取项目列表失败:', err);
        setError(err.message || '获取项目列表失败');
      } finally {
        setLoading(false);
      }
    };
    
    if (authStatus === 'authenticated') {
      fetchProjects();
    } else if (authStatus === 'unauthenticated') {
      router.push('/auth/login');
    }
    
    // 创建项目后自动刷新数据
    const refreshTimer = setTimeout(() => {
      if (authStatus === 'authenticated') {
        fetchProjects();
      }
    }, 2000); // 2秒后再次刷新
    
    return () => clearTimeout(refreshTimer);
  }, [authStatus, router, session?.user?.id]);

  // 添加手动刷新功能
  const handleRefresh = async () => {
    if (authStatus === 'authenticated') {
      setLoading(true);
      try {
        let url = '/api/project';
        if (session?.user?.id) {
          url += `?userId=${session.user.id}`;
        }
        url += `${url.includes('?') ? '&' : '?'}t=${new Date().getTime()}`;
        
        const response = await fetch(url, { 
          cache: 'no-store',
          headers: {
            'Cache-Control': 'no-cache',
            'Pragma': 'no-cache'
          }
        });
        
        if (!response.ok) {
          throw new Error(`请求失败: ${response.status}`);
        }
        
        const data = await response.json();
        if (data.success) {
          setProjects(data.data);
        } else {
          throw new Error(data.message || '刷新项目列表失败');
        }
      } catch (err: any) {
        console.error('刷新项目列表失败:', err);
        setError(err.message || '刷新项目列表失败');
      } finally {
        setLoading(false);
      }
    }
  };

  // 过滤和搜索项目
  const filteredProjects = projects.filter(project => {
    // 状态过滤
    if (filter.status !== 'all' && project.status !== filter.status) return false;
    
    // 搜索过滤
    if (searchTerm) {
      const searchLower = searchTerm.toLowerCase();
      return (
        project.name.toLowerCase().includes(searchLower) ||
        project.description?.toLowerCase().includes(searchLower) ||
        project.tags?.some(tag => tag.toLowerCase().includes(searchLower))
      );
    }
    
    return true;
  });

  // 排序项目
  const sortedProjects = [...filteredProjects].sort((a, b) => {
    const aValue = a[sort.field as keyof Project];
    const bValue = b[sort.field as keyof Project];
    
    if (typeof aValue === 'string' && typeof bValue === 'string') {
      return sort.direction === 'asc' 
        ? aValue.localeCompare(bValue) 
        : bValue.localeCompare(aValue);
    }
    
    return 0;
  });

  // 处理状态过滤变化
  const handleStatusFilterChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setFilter(prev => ({ ...prev, status: e.target.value }));
  };

  // 处理排序变化
  const handleSortChange = (field: string) => {
    setSort(prev => ({
      field,
      direction: prev.field === field && prev.direction === 'asc' ? 'desc' : 'asc',
    }));
  };

  // 如果未登录，显示加载中
  if (authStatus === 'loading') {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-pulse text-gray-500">加载中...</div>
      </div>
    );
  }

  return (
    <div className="min-h-screen">
      <main className="py-6 px-4 sm:px-6 lg:px-8 max-w-7xl mx-auto">
        <AppHeader
          title="我的项目"
          subtitle="管理和访问您参与的所有项目"
          actions={
            <div className="flex space-x-2">
              <button
                type="button"
                onClick={handleRefresh}
                className="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md shadow-sm text-gray-700 bg-white hover:bg-gray-50 focus:outline-none"
                disabled={loading}
              >
                <ArrowPathIcon className="h-5 w-5 mr-1" />
                {loading ? '刷新中...' : '刷新'}
              </button>
              <button
                type="button"
                onClick={() => router.push('/project/new')}
                className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-[var(--primary-color)] hover:bg-[var(--primary-hover)] focus:outline-none"
              >
                <PlusIcon className="h-5 w-5 mr-2" />
                新建项目
              </button>
            </div>
          }
        />

        {/* 搜索和过滤工具栏 */}
        <div className="mt-6 bg-white p-4 shadow rounded-lg">
          <div className="flex flex-col md:flex-row md:items-center md:justify-between space-y-4 md:space-y-0">
            <div className="max-w-lg w-full lg:max-w-xs">
              <label htmlFor="search" className="sr-only">搜索项目</label>
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <MagnifyingGlassIcon className="h-5 w-5 text-gray-400" aria-hidden="true" />
                </div>
                <input
                  id="search"
                  name="search"
                  className="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md leading-5 bg-white placeholder-gray-500 focus:outline-none focus:placeholder-gray-400 focus:ring-1 focus:ring-[var(--primary-color)] focus:border-[var(--primary-color)] sm:text-sm"
                  placeholder="搜索项目..."
                  type="search"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                />
              </div>
            </div>
            <div className="flex flex-col sm:flex-row sm:items-center space-y-2 sm:space-y-0 sm:space-x-4">
              <div className="flex items-center">
                <FunnelIcon className="h-5 w-5 text-gray-400 mr-2" />
                <label htmlFor="status-filter" className="text-sm font-medium text-gray-700 mr-2">
                  状态:
                </label>
                <select
                  id="status-filter"
                  value={filter.status}
                  onChange={handleStatusFilterChange}
                  className="block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md"
                >
                  <option value="all">全部</option>
                  <option value="planning">规划中</option>
                  <option value="in-progress">进行中</option>
                  <option value="completed">已完成</option>
                </select>
              </div>
              <div className="flex items-center space-x-4">
                <span className="text-sm font-medium text-gray-700">排序:</span>
                <button
                  type="button"
                  onClick={() => handleSortChange('name')}
                  className={`px-3 py-2 text-sm font-medium rounded-md ${
                    sort.field === 'name' 
                      ? 'bg-gray-100 text-gray-900' 
                      : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
                  }`}
                >
                  名称
                  {sort.field === 'name' && (
                    <ArrowsUpDownIcon className="inline-block h-4 w-4 ml-1" />
                  )}
                </button>
                <button
                  type="button"
                  onClick={() => handleSortChange('updatedAt')}
                  className={`px-3 py-2 text-sm font-medium rounded-md ${
                    sort.field === 'updatedAt' 
                      ? 'bg-gray-100 text-gray-900' 
                      : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
                  }`}
                >
                  更新时间
                  {sort.field === 'updatedAt' && (
                    <ArrowsUpDownIcon className="inline-block h-4 w-4 ml-1" />
                  )}
                </button>
              </div>
            </div>
          </div>
        </div>

        {/* 项目列表 */}
        <div className="mt-6">
          {loading ? (
            <div className="py-12 flex justify-center">
              <div className="animate-pulse flex items-center">
                <ArrowPathIcon className="h-6 w-6 animate-spin text-gray-500 mr-3" />
                <span className="text-lg font-medium text-gray-500">加载项目列表...</span>
              </div>
            </div>
          ) : error ? (
            <div className="py-12">
              <div className="text-center">
                <ExclamationCircleIcon className="mx-auto h-12 w-12 text-red-500" />
                <h3 className="mt-2 text-lg font-medium text-gray-900">加载失败</h3>
                <p className="mt-1 text-gray-500">{error}</p>
                <div className="mt-6">
                  <button
                    onClick={handleRefresh}
                    className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-red-600 hover:bg-red-700 focus:outline-none"
                  >
                    <ArrowPathIcon className="h-5 w-5 mr-2" />
                    重试
                  </button>
                </div>
              </div>
            </div>
          ) : sortedProjects.length > 0 ? (
            <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
              {sortedProjects.map((project) => (
                <div
                  key={project.id}
                  className="bg-white overflow-hidden shadow rounded-lg hover:shadow-md transition-shadow duration-200"
                >
                  <div className="px-4 py-5 sm:p-6">
                    <div className="flex items-center justify-between">
                      <Link 
                        href={`/project/${project.id}`}
                        className="text-lg font-semibold text-gray-900 hover:text-[var(--primary-color)] truncate"
                      >
                        {project.name}
                      </Link>
                      <StatusBadge status={project.status || 'planning'} />
                    </div>
                    <p className="mt-1 text-sm text-gray-600 line-clamp-2">
                      {project.description || '无项目描述'}
                    </p>
                    <div className="mt-4 flex justify-between">
                      <div className="flex items-center text-sm text-gray-500">
                        <span className="mr-2">创建者:</span>
                        <div className="flex items-center">
                          {project.owner?.avatar ? (
                            <Image
                              src={project.owner.avatar}
                              alt={project.owner.name}
                              width={20}
                              height={20}
                              className="rounded-full mr-1"
                            />
                          ) : (
                            <div className="w-5 h-5 rounded-full bg-gray-200 mr-1 flex items-center justify-center text-xs">
                              {project.owner?.name?.charAt(0) || 'U'}
                            </div>
                          )}
                          <span>{project.owner?.name || '未知用户'}</span>
                        </div>
                      </div>
                      <span className="text-sm text-gray-500">
                        {new Date(project.updatedAt).toLocaleDateString()}
                      </span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="py-12">
              <div className="text-center">
                <svg
                  className="mx-auto h-12 w-12 text-gray-400"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M9 13h6m-3-3v6m-9 1V7a2 2 0 012-2h6l2 2h6a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2z"
                  />
                </svg>
                <h3 className="mt-2 text-lg font-medium text-gray-900">暂无项目</h3>
                <p className="mt-1 text-gray-500">开始创建您的第一个项目吧！</p>
                <div className="mt-6">
                  <button
                    type="button"
                    onClick={() => router.push('/project/new')}
                    className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-[var(--primary-color)] hover:bg-[var(--primary-hover)] focus:outline-none"
                  >
                    <PlusIcon className="h-5 w-5 mr-2" />
                    新建项目
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>
      </main>
    </div>
  );
} 